#!/usr/bin/perl
use strict;
use warnings;
sub gene_cut_exon{
    if(@_ != 2){
		die "ERROR! sorte should get exactly two arguments!\n";
	}
	my($gene,$exon) = @_;
	
	#声明一个保存内含子序列的二维数组
	#my $introns;
	my $gene_line;
	my $exon_line;
	open GENE_IN,"<","$gene" or die "can't open file $gene!\n";
	open EXON_IN,"<","$exon" or die "can't open file $exon!\n"; 
	
	open INTRON,">>","introns.txt";
	open ERROR,">>","error.txt";
	#记录上一条外显子记录的最大位点值
	my $record_exon_last_index = 0;
	my $isReaded = 0;#避免外显子重复读取
	
	#tmp 记录基因的最大位点值
	my $record_gene_last_index = 0;
	while(<GENE_IN>){#每次读一行基因数据
		$gene_line = $_;
		
		#解析为数组
		my @gene_line_arr = split(/\s+/,$gene_line);
#		print "$gene_line_arr[2]";
#=pot
		#如果当前基因的最小位点大于 记录的上一条外显子最大记录位点
		if($gene_line_arr[2] >= $record_exon_last_index){
			#初始化外显子最大位点值为 基因的下标
			$record_exon_last_index = $gene_line_arr[2];
		}
		while(1){

			if(!$isReaded){
				#读一行外显子数据
				$exon_line = <EXON_IN>;
				if(eof){
					print "read end.";
					exit;
				}
				$isReaded = 1;#标志已读
			}
			#将外显子解析成数组
			my @exon_line_arr = split(/\s+/,$exon_line);
			
			#如果基因不同
			if($gene_line_arr[0] lt $exon_line_arr[0]){
				#记录基因最大位点值
				$record_gene_last_index = $gene_line_arr[3];
				last;#读一条基因
			}elsif($gene_line_arr[0] gt $exon_line_arr[0]){
				$isReaded = 0 ;
				next;#读一条外显子
			}
			
			#如果基因的大位点 < 外显子的小位点 则 读一条基因
			if($gene_line_arr[3] < $exon_line_arr[2]){
				#记录基因最大位点值
				$record_gene_last_index = $gene_line_arr[3];
				last;
			}
			
			#如果当前外显子在基因内，
			#如果满足条件，记录内含子中
			if($record_exon_last_index < $exon_line_arr[2]){
				print INTRON "$exon_line_arr[0]：introns: $record_exon_last_index,$exon_line_arr[2]\n";
			}
			
			#如果当前外显子不在基因内
			if($exon_line_arr[2] > $record_gene_last_index && $exon_line_arr[3] < $gene_line_arr[2]){
				print ERROR "$exon_line_arr[0]：error: $exon_line_arr[2],$exon_line_arr[3]\n";
			}
			#记录下外显子最大位点值
			$record_exon_last_index = $exon_line_arr[3];
			
			$isReaded = 0;#已经使用，标志可读
		}
#=cut
	}
}	
gene_cut_exon("gene.txt","exon.txt");